/** 菜单格式转换工具方法 license by http://eleadmin.com */
import EleEmptyLayout from '../ele-empty-layout';
import EleIframeLayout from '../ele-iframe-layout';
import EleRedirect from '../ele-redirect';
import { eachTreeData, formatTreeData, isUrl } from './index.js';

/**
 * 判断路由地址是否已经添加
 * @param path 路由地址
 * @param data 路由数据
 * @returns {boolean}
 */
function pathIsAdd(path, data) {
  let isAdd = false;
  eachTreeData(data, (item) => {
    if (path === item.path) {
      isAdd = true;
      return false;
    }
  });
  return isAdd;
}

/**
 * 格式化菜单数据
 * @param data 菜单数据
 * @param parseMenuItem 自定义格式菜单item
 * @returns {{homePath: String, homeTitle: String, menus: Array}}
 */
export function formatMenus(data, parseMenuItem) {
  const home = { path: null, title: null };
  const menus = formatTreeData(data, (d) => {
    const item = parseMenuItem ? parseMenuItem(d) : Object.assign({}, d);
    item.meta = Object.assign(
      {
        title: item.title,
        icon: item.icon,
        hide: item.hide,
        active: item.active || item.uid,
        hideFooter: item.hideFooter,
        hideSidebar: item.hideSidebar,
        tabUnique: item.tabUnique
      },
      item.meta
    );
    if (!item.children?.length) {
      if (!home.path && item.path && !isUrl(item.path)) {
        home.path = item.path;
        home.title = item.meta.title;
      }
    } else if (item.children[0].path) {
      const cp = item.children[0].path;
      if (!item.redirect) {
        item.redirect = cp;
      }
      if (!item.path) {
        item.path = cp.substring(0, cp.lastIndexOf('/'));
      }
    }
    if (!item.path) {
      console.error('菜单的path作为vue循环的key不能为空且要唯一: ', d);
      return false;
    }
    return item;
  });
  return {
    menus: menus,
    homePath: home.path,
    homeTitle: home.title
  };
}

/**
 * 菜单数据转成路由数据
 * @param menus 菜单数据
 * @param importComponent 加载组件的方法
 * @param added 已添加的路由
 * @param redirect 是否需要刷新页面的路由
 * @returns {Array}
 */
export function menuToRoutes(menus, importComponent, added, redirect) {
  if (!menus?.length) {
    return null;
  }
  const routes = [],
    addedRoutes = added ? [].concat(added) : [];
  if (redirect !== false) {
    routes.push({
      path: '/redirect',
      component: EleEmptyLayout,
      children: [
        {
          path: '*',
          component: EleRedirect
        }
      ]
    });
  }
  menus.forEach((item) => {
    const path =
      item.path && item.path.includes('?')
        ? item.path.substring(0, item.path.indexOf('?'))
        : item.path;
    if (path && !isUrl(path) && !pathIsAdd(path, addedRoutes)) {
      const meta = Object.assign({}, item.meta);
      let component;
      if (item.component) {
        if (isUrl(item.component)) {
          component = EleIframeLayout;
          meta.iframe = item.component;
          meta.hideFooter = true;
        } else {
          component = function() {
            return importComponent(item.component);
          };
        }
      } else {
        component = EleEmptyLayout;
      }
      addedRoutes.push({ path: item.path });
      routes.push({
        meta: meta,
        name: item.path,
        path: item.path,
        component: component,
        redirect: item.redirect,
        children: menuToRoutes(item.children, importComponent, addedRoutes)
      });
    }
  });
  return routes;
}
